package com.example.tass.controller;

import cn.tass.SRJ1933.devices.inf.TassSignServerApi;
import cn.tass.SRJ1933.devices.params.response.cert.*;
import cn.tass.exceptions.TAException;
import com.example.tass.common.ResultMessage;
import com.example.tass.constant.Constants;
import com.example.tass.domain.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CertificateTest_3_10 {
    private static String printFormat = "错误码[%d]\n错误消息[%s]\n接口结果： %s\n";
    private static final Logger logger = LoggerFactory.getLogger(CertificateTest_3_10.class);
    private TassSignServerApi signServerApi;

    public CertificateTest_3_10(TassSignServerApi signServerApi) {
        this.signServerApi = signServerApi;
    }

    // 3.10.1 列举根证书标识
    @GetMapping(value = "/listRootCertIds")
    public ResultMessage listRootCertIds() {
        try {
            ListRootCertIdsResponse response = signServerApi.listRootCertIds();
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("生成对称密钥（生成对称密钥 – 明文返回）： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getRootCertIds()));
                return ResultMessage.newSuccessResult(response.getRootCertIds().toString());
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.2 导出根证书
    @GetMapping(value = "/exportRootCert")
    public ResultMessage exportRootCert() {
        try {
            ExportRootCertResponse response = signServerApi.exportRootCert("OCA");
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("生成对称密钥（生成对称密钥 – 明文返回）： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getCert()));
                return ResultMessage.newSuccessResult(response.getCert());
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.3 导入根正书
    @GetMapping(value = "/importRootCert")
    public ResultMessage importRootCert(@RequestBody MyImportRooCertRequest request) {
        try {
            ImportRootCertResponse response = signServerApi.importRootCert(request.getRootCertId(), request.getParentRootCertId(), request.getCert());
            if (response.getCode() != 0) {  // code = 134217751 对应十六进制：0x08000017，在文档中查询对应错误码：数据已存在	data is existed
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("生成对称密钥（生成对称密钥 – 明文返回）： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getMsg()));
                return ResultMessage.newSuccessResult(Constants.IMPORT_CERT_SUCCESS);
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.4 导出密钥对证书
    @GetMapping(value = "/exportKeyPairCert")
    public ResultMessage exportKeyPairCert(@RequestBody MyExportKeyPairCertRequest request) {
        try {
            ExportKeyPairCertResponse response = signServerApi.exportKeyPairCert(request.getKeyId(), request.getCertType());
            if (response.getCode() != 0) {  // code = 134217751 对应十六进制：0x08000017，在文档中查询对应错误码：数据已存在	data is existed
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("生成对称密钥（生成对称密钥 – 明文返回）： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getSignCert() + ", " + response.getEncCert()));
                CertKeyPair certKeyPair = new CertKeyPair();
                certKeyPair.setSignCert(response.getSignCert());
                certKeyPair.setEncCert(response.getEncCert());
                ResultMessage resultMessage = ResultMessage.newSuccessResult();
                resultMessage.setData(certKeyPair);
                return resultMessage;
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.5 导出业务证书
    @GetMapping(value = "/exportUserCert")
    public ResultMessage exportUserCert(@RequestBody MyExportUserCertRequest request) {
        try {
            ExportUserCertResponse response = signServerApi.exportUserCert(request.getCertId(), request.getCertIdType(), request.getIsSign());
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("生成对称密钥（生成对称密钥 – 明文返回）： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getCert()));
                return ResultMessage.newSuccessResult(response.getCert());
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.6 删除用户证书
    @GetMapping(value = "/delUserCert")
    public ResultMessage delUserCert(@RequestBody MyDelUserCertRequest request) {
        try {
            DelRootCertResponse response = signServerApi.delUserCert(request.getCertId(), request.getCertIdType(), request.isSign());
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("删除用户证书： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getMsg()));
                return ResultMessage.newSuccessResult(Constants.DEL_USER_CERT_SUCCESS);
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.7 导入业务证书
    @GetMapping(value = "/importUserCert")
    public ResultMessage importUserCert(@RequestBody MyImportUserCertRequest request) {
        try {
            ImportUserCertResponse response = signServerApi.importUserCert(request.getCertId(), request.getCert(), request.getCertType(),
                    request.getRootCertId(), request.isOverwrite());
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("导入业务证书： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getMsg()));
                return ResultMessage.newSuccessResult(Constants.IMPORT_USER_CERT_SUCCESS);
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.8 检查用户证书是否存在
    @GetMapping(value = "/existUserCert")
    public ResultMessage existUserCert(@RequestBody MyExistUserCertRequest request) {
        try {
            ExistUserCertResponse response = signServerApi.existUserCert(request.getCertId(), request.getCertIdType(), request.getIsSign(), request.isValid());
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("检查用户证书是否存在： " + String.format(printFormat, response.getCode(), response.getMsg(), response.isExist()));
                return ResultMessage.newSuccessResult(String.valueOf(response.isExist()));
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.10.9 获取证书信息
    @GetMapping(value = "/getCertInfo")
    public ResultMessage getCertInfo(@RequestBody MyGetCertInfoRequest request) {
        try {
            GetCertInfoResponse response = signServerApi.getCertInfo(request.getCert(), request.getInfoType());
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("证书信息： "+response.toString());
                ResultMessage resultMessage = ResultMessage.newSuccessResult();
                resultMessage.setData(response);
                return resultMessage;
            }

        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }
    
    // 3.10.10 校验证书
    @GetMapping(value = "/validateCert")
    public ResultMessage validateCert(@RequestBody MyValidateCertRequest request){
        try {
            ValidateCertResponse response = signServerApi.validateCert(request.getCert(), request.getVerifyLevel());
            if (response.getCode() != 0) {
                logger.error(response.getMsg());
                return ResultMessage.newFailureResult(response.getMsg());
            } else {
                System.out.println("导入业务证书： " + String.format(printFormat, response.getCode(), response.getMsg(), response.getMsg()));
                return ResultMessage.newSuccessResult(Constants.VALIDATE_CERT_SUCCESS);
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }
}
